package cn.ahaoweb.drule.core;


import cn.ahaoweb.drule.core.callback.AfterCreateSessionCallback;
import cn.ahaoweb.drule.core.configuration.ConfigurationImpl;
import cn.ahaoweb.drule.core.configuration.Option;
import cn.ahaoweb.drule.core.exception.DruleRuleServiceException;
import cn.ahaoweb.drule.core.configuration.Configuration;
import cn.ahaoweb.drule.core.configuration.RuleServiceConfiguration;
import cn.ahaoweb.drule.core.constant.RuleType;
import org.kie.api.KieBase;
import org.kie.api.KieBaseConfiguration;
import org.kie.api.builder.Message;
import org.kie.api.builder.Results;
import org.kie.api.conf.EqualityBehaviorOption;
import org.kie.internal.utils.KieHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;

/**
 * @Name: 规则服务
 * @Description:
 * @Author: wangzhonghao
 * @Date: 2025/2/12 15:34
 */
public class RuleServiceImpl implements RuleService {

    public static final AtomicInteger ATOMIC_INTEGER = new AtomicInteger(0);

    public static final String DEFAULT_VERSION = "1";

    public static final String DEFAULT_PACKAGE = "cn.ahaoweb.drule";

    // 唯一标识符
    protected String identifier;

    // 版本号
    protected String version;

    // 包
    protected String pkg;

    // 配置信息
    protected Configuration config;

    // 规则文件内容
    protected Map<RuleType, List<String>> fileContents;

    // 事实对象类型选择器
    protected FactClassSelector factClassSelector;

    // 规则会话创建后回调函数
    protected AfterCreateSessionCallback afterCreateSessionCallback;

    // Kie
    private KieHelper kieHelper;

    // 知识库
    protected KieBase kieBase;

    public RuleServiceImpl() {
        this(null);
    }

    public RuleServiceImpl(String identifier) {
        this(identifier, null);
    }

    public RuleServiceImpl(String identifier, String version) {
        this(identifier, version, null);
    }

    public RuleServiceImpl(String identifier, String version, String pkg) {
        this(identifier, version, pkg, null);
    }

    /**
     * 构建规则执行服务
     *
     * @param identifier 唯一标识符
     * @param version    版本号
     * @param pkg        包名
     * @param config     配置
     */
    public RuleServiceImpl(String identifier, String version, String pkg, Configuration config) {
        this.identifier = identifier == null ? "RuleService$" + ATOMIC_INTEGER.incrementAndGet() : identifier;
        this.version = version == null ? DEFAULT_VERSION : version;
        this.pkg = pkg == null ? DEFAULT_PACKAGE : pkg;
        this.config = config == null ? defaultConfiguration() : defaultConfiguration().merge(config);
        this.fileContents = new HashMap<>();
    }

    private static ConfigurationImpl defaultConfiguration() {
        ConfigurationImpl configuration = new ConfigurationImpl();
        configuration.setProperty(RuleServiceConfiguration.RULE_CONTENT_CACHE.OPEN);
        configuration.setProperty(RuleServiceConfiguration.EXECUTE_MODE.EXECUTE);
        return configuration;
    }

    /**
     * 添加规则内容
     * <pre>
     *     添加的内容，需要重新初始化 {@link RuleServiceImpl#init()} 才会生效
     * </pre>
     *
     * @param type
     * @param content
     * @return
     */
    public RuleService addContent(RuleType type, String content) {
        if (this.fileContents.get(type) == null) {
            this.fileContents.put(type, new ArrayList<>());
        }
        this.fileContents.get(type).add(content);
        return this;
    }

    /**
     * 获取所有规则文件
     *
     * @return 一个Map集合，键为规则类型（RuleType），值为对应规则文件的字符串列表（List<String>）
     */
    public Map<RuleType, List<String>> getRuleFiles(){
        return getFileContents();
    }

    /**
     * 初始化规则服务
     * <pre>
     *     当前主要用于初始化知识库kieBase，同时如果需要重新生成kieBase也可以调用该服务
     * </pre>
     *
     * @return
     */
    public RuleService init() throws DruleRuleServiceException{
        kieHelper = new KieHelper();
        if (fileContents.size() < 1) {
            throw new DruleRuleServiceException("需要编译规则内容为空：" + identifier + "，请添加规则内容");
        } else {
            for (Map.Entry<RuleType, List<String>> entry : fileContents.entrySet()) {
                for (String content : entry.getValue()) {
                    kieHelper.addContent(content, entry.getKey().getType());
                }
            }
        }
        // 效验文件内容
        Results verify = kieHelper.verify();
        if (verify.hasMessages(Message.Level.ERROR)) {
            List<Message> messages = verify.getMessages();
            StringBuilder errors = new StringBuilder();
            for (Message message : messages) {
                errors.append(message.getText()).append("\n");
            }
            throw new DruleRuleServiceException("效验文件内容出现异常：\n" + errors);
        }
        kieBase = kieHelper.build(buildKieBaseConfiguration());
        // 一些后置处理操作，主要是配置方面的
        initPostProcess();
        return this;
    }

    /**
     * 后置处理操作
     *
     * @return
     */
    protected RuleService initPostProcess() {
        if (config.exist(RuleServiceConfiguration.RULE_CONTENT_CACHE.CLOSE)) {
            // 不缓存文件内容，则会清空，注意下次重新初始化时需要重新添加所有的规则文件内容
            this.fileContents = new HashMap<>();
        }
        return this;
    }

    @Override
    public RuleSession createSession() {
        RuleSessionImpl ruleSession;
        if (config.exist(RuleServiceConfiguration.EXECUTE_MODE.DEBUG)
                || config.exist(RuleServiceConfiguration.EXECUTE_MODE.INFO)) {
            ruleSession = new DebugRuleSessionImpl(this);
        } else {
            ruleSession = new RuleSessionImpl(this);
        }
        if (afterCreateSessionCallback == null){
            return ruleSession;
        }
        return afterCreateSessionCallback.afterCreateSession(ruleSession);
    }

    @Override
    public RuleService afterCreateSessionCallback(AfterCreateSessionCallback callback) {
        this.afterCreateSessionCallback = callback;
        return this;
    }

    protected KieBaseConfiguration buildKieBaseConfiguration() {
        KieBaseConfiguration kieBaseConfiguration = kieHelper.ks.newKieBaseConfiguration();
        kieBaseConfiguration.setOption(EqualityBehaviorOption.EQUALITY);
        return kieBaseConfiguration;
    }

    public String getIdentifier() {
        return identifier;
    }

    public String signature() {
        return identifier + ":v" + version;
    }

    public String getVersion() {
        return version;
    }

    public String getPkg() {
        return pkg;
    }

    public Configuration getConfig() {
        return config;
    }

    public Map<RuleType, List<String>> getFileContents() {
        return fileContents;
    }

    public KieBase getKieBase() {
        return kieBase;
    }

    public RuleService addConfig(String name, String value) {
        config.setProperty(name, value);
        return this;
    }

    public RuleService addConfig(Option option) {
        config.setProperty(option);
        return this;
    }

    public RuleService factClassSelector(FactClassSelector selector){
        this.factClassSelector = selector;
        return this;
    }

    @Override
    public FactClassSelector getFactClassSelector() {
        return factClassSelector;
    }

}
